package com.shell.customer.accreditation.rx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.customer.accreditation.AccreditEvent;
import com.shell.customer.accreditation.vo.AccreditationVo;
import com.shell.customer.base.service.CusAcctService;
import com.shell.customer.base.service.CusAcctUseService;
import com.shell.customer.po.CusAcct;
import com.shell.customer.po.CusAcctUse;
import com.shell.customer.po.CusRec;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;

@Component
public class UpdateCuAcctSubscriber extends OnErrorNotImplementedSubscriber<AccreditEvent> {
	@Autowired
	private CusAcctService pubCusAcctService;
	@Autowired
	private CusAcctUseService cusAcctUseService;

	public void onApplicationEvent(AccreditEvent event) {
		AccreditationVo accreditationVo = event.getAccreditationVo();
		CusRec cus = accreditationVo.getCustomerC();

		CusAcct cusAcct = accreditationVo.getCusAcct();
		if (StringUtil.empty(cusAcct.getAcctId())) {
			cusAcct.setAcctId(SystemUtil.getUUID());
		}
		cusAcct.setAcctState("N");
		cusAcct.setAcctType("0");
		cusAcct.setCreateTime(DateUtil.getSystemDateTime());
		cusAcct.setCusId(cus.getCusId());
		saveOrUpdateCusAcctUse(cusAcct.getAcctNo(), cusAcct.getAcctId());
		this.pubCusAcctService.saveOrUpdate(cusAcct);
	}

	private void saveOrUpdateCusAcctUse(String acctNo, String acctId) {
		CusAcctUse acctUse = new CusAcctUse();
		acctUse.setUseCode("00");
		if (!StringUtil.emptyAndNull(acctId)) {
			CusAcct cusAcct = (CusAcct) this.pubCusAcctService.selectByKey(acctId);
			if (cusAcct != null) {
				acctUse.setAcctNo(cusAcct.getAcctNo());
				CusAcctUse oldAcctUse = (CusAcctUse) this.cusAcctUseService.selectOne(acctUse);
				this.cusAcctUseService.deleteEntity(oldAcctUse);
			}
		}
		acctUse.setAcctNo(acctNo);
		this.cusAcctUseService.saveOrUpdate(acctUse);
	}
}
